import axios from 'axios'
import store from '@/store/index'
import {showLoading, hideLoading} from './Loading';
// axios.defaults.baseURL = '/api'
axios.defaults.withCredentials = true
const apis = {
  production: 'http://localhost:8686', // 线上 (生产环境)
  development: 'http://localhost:8686', // 本地 (开发环境)
  accessHomeData: '' // 其他api
}

export const baseUrl = process.env.NODE_ENV === 'production' ? apis.production : apis.development
// export const baseUrl = apis.development
export const request = (options) => {
  return new Promise((resolve, reject) => {
    axios({
      method: options.method,
      url: `${baseUrl}${options.url}`,
      data: options.data,
      timeout: 6000,
      responseType: options.responseType?options.responseType:'json',
      params: options.params,
      transformRequest: [function (data) {
        if (options.noJson) { // 判断是否json格式或者是表单提交形式
          let ret = '';
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret // 便于直接取到内部data
        }
        return JSON.stringify(data)
      }],
      headers: {
        ...options.headers,
        // 认证和请求方式
        'Content-Type': options.noJson? 'application/x-www-form-urlencoded':'application/json',
        // 'authorization':'admin',
        'token': store.state.token,

      }
    }).then(res => {
      if (options.getHeader) {
        resolve(res)
      }else{
        resolve(res.data)
      }
    }).catch(err => {
      reject(err.data)
    })
  })
};

// uploadFileRequest  图片上传
export const uploadFileRequest = (url, data) => {
  return axios({
    method: 'post',
    url: `${baseUrl}${url}`,
    data: data,
    headers: {
      'Content-Type': 'multipart/form-data',
      'token': localStorage.getItem('token'),
      'authorization': 'admin'
    }
  })
};

// post
export const post = (options) => {
  options.method = 'post'
  options.data = options.params
  options.params = null
  return request(options)
};


// get
// responseType可以设置响应的数据类型为一个包含二进制数据的 Blob 对象,用于下载流文件
export const get = (options) => {
  options.method = 'get'
  options.data = null
  return request(options)
};

// 使用拦截器添加加载动画
axios.interceptors.request.use(
  config => {
    showLoading();
    return config
  },
  err => {
    hideLoading();
    return Promise.reject(err)
  }
);
// 关闭加载动画
axios.interceptors.response.use(
  response => {
    hideLoading();
    // console.log(response.headers)
    return response;
  },
  error => {
    hideLoading();
    return error.response;
  }
);
